<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/11/9
 * Time: 17:28
 */

namespace app\mall\controller;


use app\mall\model\User;
use app\mall\service\LoginService;
use app\Request;
use app\Utils\Util;

class Login extends BaseController
{
    /**
     * 账号登录
     */
    public function account(Request $request, LoginService $service)
    {
        $username = (string)$request->param('username');
        $password = (string)$request->param('password');
        if (empty($username))
            return Util::returnJson(self::CODE_ERROR, [], $msg = "账号不能为空");
        $login_info = $service->accountLogin($username, $password);
        if ($login_info['code'] == 1) {
            $token = signToken($login_info['msg']['id']);
            return Util::returnJson(self::CODE_SUCCESS, ['access_token' => $token], "登录成功");
        }
        return Util::returnJson(self::CODE_ERROR, [], $msg = $login_info['msg']);
    }


    /**
     * @param User $user
     * @return array
     */
    public function respondWithToken(User $user): array
    {
        // 直接创建token并设置有效期
        $token = signToken($user['id']);
        return [
            'token' => $token,
            'account' => $user['account'],
            'head_img' => $user['head_img'],
            'nickname' => $user['nickname'],
        ];
    }
}